using System.Linq;
using System.Data.Linq;
using Quickie.Models;
using Quickie.Models.IoC;
using Quickie.Models.Data;
using Quickie.Models.Entities;
using Quickie.Models.ViewModel;
using Quickie.Models.Interfaces;

namespace Quickie.Models.Data
{
    /// <summary>
    /// Klasa koja predstavlja LINQ2SQL provider
    /// </summary>
    public class L2SDataProvider : IDataProvider
    {
        private DataClassesDataContext context;

        /// <summary>
        /// Konstruktor klase
        /// </summary>
        public L2SDataProvider()
        {
            context = new DataClassesDataContext();
        }

        /// <summary>
        /// Metoda koja vraca "tablicu" podataka iz baze
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IQueryable<T> Linq<T>() where T : class,IEntity
        {
            return context.GetTable<T>().AsQueryable();
        }

        /// <summary>
        /// Metoda koja unosi odredeni entitet T u bazu podataka
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public void Insert<T>(T entity) where T : class, IEntity
        {
            if (entity.ID == 0)
                context.GetTable<T>().InsertOnSubmit(entity);
            else
            {
                var original = context.GetTable<T>().GetOriginalEntityState(entity);
                if (original == null) context.GetTable<T>().Attach(entity);
                context.Refresh(RefreshMode.KeepCurrentValues, entity);
            }
        }

        /// <summary>
        /// Metoda koja brise odredeni entitet iz baze podataka
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        public void Delete<T>(T entity) where T : class, IEntity
        {
            context.GetTable<T>().DeleteOnSubmit(entity);
        }

        /// <summary>
        /// Metoda koja sprema sve promjene u bazu podataka
        /// </summary>
        public void SubmitChanges()
        {
            context.SubmitChanges();
        }
    }
}